package cn.wangxl.group.rpc.protocol;

import cn.wangxl.group.rpc.rpcEntity.RpcRequest;
import cn.wangxl.group.rpc.rpcEntity.RpcResponse;
import com.alibaba.fastjson.JSON;

/**
 * @Deacription JsonMessageProtocol
 * @Author 20112128
 * @Date 2020/9/18 10:16
 **/
public class JsonMessageProtocol implements MessageProtocol{

    @Override
    public byte[] marshallingRequest(RpcRequest rpcRequest) {
        if(rpcRequest.getParameters()!=null
                && rpcRequest.getParameters().length>0){
            Object[] params = rpcRequest.getParameters();
            Object[] serialParams = new Object[params.length];
            for(int i=0;i<params.length;i++){
                serialParams[i] = JSON.toJSONString(params[i]);
            }

            rpcRequest.setParameters(serialParams);
        }
        return JSON.toJSONBytes(rpcRequest);
    }
    @Override
    public RpcRequest unmarshallingRequest(byte[] data) {
        Object object = JSON.parse(data);
        return (RpcRequest)object;
    }
    @Override
    public byte[] marshallingResponse(RpcResponse rpcResponse) {
        return JSON.toJSONBytes(rpcResponse);
    }
    @Override
    public RpcResponse unmarshallingResponse(byte[] data) {
        Object object = JSON.parse(data);
        return (RpcResponse)object;
    }
}
